<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>智能财务共享中心</h2>
      </div>
      <el-form
          ref="formRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              autocomplete="username"
              placeholder="用户名"
              prefix-icon="User"
              tabindex="1"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              autocomplete="current-password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
              tabindex="2"
              type="password"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
        </el-form-item>
        <el-button
            :loading="loading"
            class="login-button"
            type="primary"
            @click="handleLogin"
        >
          登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {getUserInfo, login} from '@/api/user';
import {setToken, setUserInfo} from '@/utils/storage';

// 获取路由实例和当前路由信息
const router = useRouter();
const route = useRoute();

// 记录重定向页面路径
const redirectPath = ref(route.query.redirect as string || '');

// 登录表单引用
const formRef = ref();

// 登录加载状态
const loading = ref(false);

// 登录表单数据
const loginForm = reactive({
  username: 'admin',
  password: '',
  remember: false
});

// 表单验证规则
const loginRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 5, max: 20, message: '密码长度应在5-20个字符之间', trigger: 'blur'}
  ]
};

// 处理登录
const handleLogin = async () => {
  try {
    // 表单验证
    await formRef.value.validate();

    // 开始登录操作
    loading.value = true;

    // 调用登录API
    const result = await login({
      username: loginForm.username,
      password: loginForm.password
    });

    // 检查响应结构，确保有token字段
    if (!result.data || !result.data.token) {
      throw new Error('服务器返回的数据格式不正确');
    }

    // 保存token到localStorage
    setToken(result.data.token);

    // 获取用户信息
    const userInfoResult = await getUserInfo();

    // 保存用户信息
    if (userInfoResult.data) {
      setUserInfo(userInfoResult.data);
    }

    // 登录成功提示
    ElMessage.success('登录成功');

    // 重定向到首页或者指定页面
    router.push({path: redirectPath.value || '/dashboard'});
  } catch (error: any) {
    console.error('登录错误', error);

    // 处理特定类型的错误
    if (error.code === 401) {
      // 401 错误通常表示用户名或密码错误
      ElMessage.error({
        message: '用户名或密码错误，请重试',
        type: 'error',
        duration: 3000,
        showClose: true,
        center: true
      });
    } else if (error.code === 403) {
      // 403 错误通常表示没有权限访问
      ElMessage.error({
        message: '账号无权限或已被禁用',
        type: 'error',
        duration: 3000,
        showClose: true,
        center: true
      });
    } else if (error.message && error.message.includes('密码')) {
      // 密码相关错误
      ElMessage.error({
        message: error.message,
        type: 'error',
        duration: 3000,
        showClose: true,
        center: true
      });
    } else {
      // 其他错误
      ElMessage.error({
        message: error.message || '登录失败，请检查网络连接',
        type: 'error',
        duration: 3000,
        showClose: true,
        center: true
      });
    }

    // 如果是密码错误，清空密码字段
    if (error.code === 401 || (error.message && error.message.includes('密码'))) {
      loginForm.password = '';
    }
  } finally {
    loading.value = false;
  }
};

// 页面加载时可以执行的操作
onMounted(() => {
  // 可以在此处添加页面加载时需要执行的逻辑
  // 例如从本地存储加载保存的用户名等
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #409eff;
  font-weight: 600;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  margin-top: 15px;
}
</style> 